package org.cfk.asyncdownloadtutorial.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.cfk.asyncdownloadtutorial.constant.Const;
import org.cfk.asyncdownloadtutorial.dto.AsyncDownloadJobDTO;
import org.cfk.asyncdownloadtutorial.dto.CsvDownloadRequest;
import org.cfk.asyncdownloadtutorial.dto.ExcelDownloadRequest;
import org.cfk.asyncdownloadtutorial.service.AsyncDownloadJobService;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/async-download")
@RequiredArgsConstructor
public class AsyncDownloadController {

    private final AsyncDownloadJobService asyncDownloadJobService;
    private final KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 创建CSV导出任务
     */
    @SneakyThrows
    @PostMapping("/csv")
    public ResponseEntity<Long> createCsvDownloadJob(@RequestBody CsvDownloadRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();
        Long jobId = asyncDownloadJobService.createAsyncDownloadJob(
                "csv",
                objectMapper.writeValueAsString(request),
                 "example.csv"
        );
        kafkaTemplate.send(Const.KAFKA_TOPIC_ASYNC_DOWNLOAD_JOB, jobId.toString());
        return ResponseEntity.ok(jobId);
    }

    /**
     * 创建Excel导出任务
     */
    @SneakyThrows
    @PostMapping("/excel")
    public ResponseEntity<Long> createExcelDownloadJob(@RequestBody ExcelDownloadRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();
        Long jobId = asyncDownloadJobService.createAsyncDownloadJob(
                "excel",
                objectMapper.writeValueAsString(request),
                "example.xlsx"
        );
        kafkaTemplate.send(Const.KAFKA_TOPIC_ASYNC_DOWNLOAD_JOB, jobId.toString());
        return ResponseEntity.ok(jobId);
    }

    /**
     * 获取任务状态
     */
    @GetMapping("/{jobId}/status")
    public ResponseEntity<AsyncDownloadJobDTO> getJobStatus(@PathVariable Long jobId) {
        AsyncDownloadJobDTO job = asyncDownloadJobService.getById(jobId);
        if (job == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(job);
    }

    /**
     * 下载文件
     */
    @GetMapping("/{jobId}/download")
    public ResponseEntity<String> downloadFile(@PathVariable Long jobId) {
        AsyncDownloadJobDTO job = asyncDownloadJobService.getById(jobId);
        if (job == null || !"SUCCESS".equals(job.getStatus())) {
            return ResponseEntity.badRequest().body("文件未准备好或任务不存在");
        }

        return ResponseEntity.ok(job.getFilePath());
    }
}